package cn.tedu.chaging.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json和对象转换工具
 */
public class JsonUtils {

    //定义对象转换工具ObjectMapper jackson
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 对象转换为json
     * @param obj
     * @return
     */
    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * json转对象
     * @param json
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
    public static  <T> T convertValue(Object object,  Class<T> clazz) {
        return objectMapper.convertValue(object,clazz);
    }
}
